package mo_gorm

import (
	"MoSkeleton/framework/core/config/properties_db"
	"MoSkeleton/framework/core/moerrors"
	_ "github.com/go-sql-driver/mysql"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
)

type MoMysqlDb struct {
}

func (m *MoMysqlDb) GenDb(dbConfig *properties_db.GeneralDBProvider, testConn bool) (db *gorm.DB, err error) {
	dbProvider := *dbConfig
	if mysqlConfig, ok := dbProvider.(*properties_db.Mysql); ok {
		return m.genMysqlByConfig(mysqlConfig, testConn)
	}
	return nil, moerrors.NewWithMsg("dbConfig is not mysql")
}

func (m *MoMysqlDb) genMysqlByConfig(dbConfig *properties_db.Mysql, testConn bool) (*gorm.DB, error) {
	if !testConn && dbConfig.Dbname == "" {
		return nil, moerrors.NewWithMsg("db name not config")
	}
	mysqlConfig := mysql.Config{
		DSN:                       dbConfig.Dsn(testConn), // DSN data source name
		DefaultStringSize:         191,                    // string 类型字段的默认长度
		SkipInitializeWithVersion: false,                  // 根据版本自动配置
	}
	if db, err := gorm.Open(mysql.New(mysqlConfig), gormConfig(&dbConfig.GeneralDB, dbConfig.Prefix, dbConfig.Singular)); err != nil {
		return nil, moerrors.New(err)
	} else {
		var engine string
		if dbConfig.Engine == "" {
			engine = "InnoDB"
		} else {
			engine = dbConfig.Engine
		}
		db.InstanceSet("gorm:table_options", "ENGINE="+engine)
		sqlDB, _ := db.DB()
		sqlDB.SetMaxIdleConns(dbConfig.MaxIdleConns)
		sqlDB.SetMaxOpenConns(dbConfig.MaxOpenConns)
		return db, nil
	}
}
